package com.ruike.alisurface.ui.settings;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.coll.CollectionAPI;
import com.alipay.iot.sdk.coll.TradeDataConstants;
import com.alipay.zoloz.smile2pay.service.Zoloz;
import com.alipay.zoloz.smile2pay.service.ZolozCallback;
import com.cunoraz.gifview.library.GifView;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

import static com.alipay.iot.sdk.coll.TradeDataConstants.TradeFailType.NETWORK_EXCEPTION;
import static com.alipay.iot.sdk.coll.TradeDataConstants.TradeFailType.NONE;

public class AliFaceTest_Aty extends BaseAty  implements ApiListener {



    @BindView(R.id.face_text)
    TextView face_text;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_aliface;
    }


    public static final String KEY_INIT_RESP_NAME = "zim.init.resp";
    public static final String CAPTURE_UI_MODE = "captureUIMode";
    static final String CODE_SUCCESS = "1000";
    static final String CODE_TIMEOUT = "1004";

    static final String TXT_OTHER = "抱歉未支付成功，请重新支付";
    Zoloz zoloz;
//    private MyCountDownTimer countDownTimer;

    String mchid;

    @Override
    protected void initViews() {
        L.i("刷脸支付测试页==" + this.getClass().getName());
        face_text.setText("正在调起刷脸摄像头");
        mchid = SharedUtils.getInstance().getString(ShareKey.MCH_ID, "");
        HandlerShow();
    }

    @Override
    protected void initData() {
        startAlFace();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(15, null, Settings_Aty.class);

    }



    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (messageHandler != null) {
            messageHandler.removeCallbacksAndMessages(null);
        }
    }

    Handler messageHandler;

    private void HandlerShow() {
        messageHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1:

                        break;
                    case 2:
//                        ToastUtils.ToastCostom(PayAlFaceActivity.this, "网络不佳，请使用微信支付宝扫码支付！！", "1", 3000);
                        showErrorToast("网络不佳，请使用微信支付宝扫码支付！！");

                        finish();
                        break;
                    case 3:

                        finish();
                        break;
                    case 4:
                        showErrorToast("网络不佳，请稍后重试！！");
                        finish();
                        break;
                    case 5:
                        face_text.setText("人脸识别完成，开启发起支付");
                        break;
                    case 6:
                        finish();
                        break;
                    case 7:
                        showErrorToast("支付失败");
                        finish();
                        break;
                }

                return false;
            }
        });
    }

    Double pay_fee;
    String orderId;








    //填写商户信息
    private HashMap<String, Object> mockInfo() {
        HashMap<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("merchantId", "2088821660782062");//必填项，签约商户的pid。来自蚂蚁开放平台，示例："2088011211821038"
        merchantInfo.put("partnerId", "2088821660782062");//必填项，ISV的pid。对于自用型商户，填写签约商户的pid，和merchantId保持一致
        merchantInfo.put("appId", "2018110962091551");//必填项，支付宝分配给开发者的应用ID，和当面付请求的appid保持一致。
        merchantInfo.put("deviceNum", mchid);//必填项，商户机具终端编号，和当面付请求的terminal_id 保持一致
        merchantInfo.put("terminal_id", mchid);
        merchantInfo.put("brandCode", "rk");
        merchantInfo.put("storeCode", mchid);//可选，商户门店编号，和当面付请求的store_id保持一致。
        return merchantInfo;
//        merchantInfo.put("alipayStoreCode","XXX");//可选，支付宝内部门店编号，如2017100900077000000045877777，和当面付请求中的alipay_store_id保持一致。
    }

    public void startAlFace() {
        /*
         * 1. 在商户APP启动时调用刷脸应用预热
         */
        zoloz = Zoloz.getInstance(getApplicationContext());
        zoloz.zolozInstall(mockInfo());

//        Toast.makeText(this, "刷脸预热完成", Toast.LENGTH_SHORT).show();

        /*
         * 2.获取设备信息
         */
        zoloz.zolozGetMetaInfo(mockInfo(), new ZolozCallback() {
            @Override
            public void response(Map map) {
                String code = (String) map.get("code");
                String metaInfo = (String) map.get("metainfo");
                L.i(" 刷脸设备  response: 获取设备信息===" + code + "=====" + metaInfo);
//                Toast.makeText(MedicalImgShowActivity.this, "response: 获取设备信息==="+ code + "=====" + metaInfo, Toast.LENGTH_SHORT).show();
                if (CODE_SUCCESS.equalsIgnoreCase(code) && metaInfo != null) {
                    /*
                     * 3.将metaInfo发送给商户服务端，由商户服务端发起刷脸初始化OpenAPI的调用
                     */

                    MchApiHttp.getInitialize( metaInfo,AliFaceTest_Aty.this);

                }
            }
        });

    }

    /**
     * 发起刷脸支付请求.
     *
     * @param txt toast文案
     */
    void promptText(final String txt) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_LONG).show();
            }
        });
    }

    String fToken;
    private long startTime, lastTime, actTime;

    /**
     * 唤起人脸识别
     */
    private void Smile(String zimId, String protocal) {
//        promptText("唤起人脸识别方法执行");
        Map<String, String> params = new HashMap<>();
        params.put(KEY_INIT_RESP_NAME, protocal);
        params.put(CAPTURE_UI_MODE, "0"); // 刷脸UI模式：0-最早版本，自动开始刷脸
        zoloz.zolozVerify(zimId, params, new ZolozCallback() {
            @Override
            public void response(Map map) {
                if (map == null) {
                    promptText(TXT_OTHER);
                    messageHandler.sendEmptyMessage(6);
                    return;
                }
                String code = (String) map.get("code");
                fToken = (String) map.get("ftoken");
                L.i("===tjf===Smile: 方法执行===" + fToken +
                        "==map="+ GsonUtils.toJson(map)+ "===code===" + code);
                //刷脸成功
                if (CODE_SUCCESS.equalsIgnoreCase(code) && fToken != null) {
                    L.i("===tjf===Smile:唤起人脸识别: ===fToken===" + fToken + "===code===" + code);
                    /*
                     * 发送订单信息 并完成支付
                     */
                    startTime = System.currentTimeMillis();

                    messageHandler.sendEmptyMessage(5);

                } else if (CODE_TIMEOUT.equalsIgnoreCase(code)) {


                    messageHandler.sendEmptyMessage(2);
                } else {

                    messageHandler.sendEmptyMessage(6);
                }
            }
        });
    }





    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        JSONObject object = null;
        try {
            object = requestJson;
            String code = object.getString("code");
            String data = object.optString("data");
            JSONObject datas = new JSONObject(data);

            if (requestUrl.endsWith("CreareSmilePayOrder") || requestUrl.endsWith("CreateForProduct")) {
                pay_fee = datas.optDouble("Pay_fee");
                orderId = datas.optString("orderId");


                startAlFace();
            } else if (requestUrl.endsWith("Initialize")) {

                String SzimId = datas.getString("zimId");
                String SzimInitClientData = datas.getString("zimInitClientData");

                //如果返回code为0 就唤醒人脸识别s
                if (code.equals("0")) {
                    L.i("=====tjf====发送成功 返回结果");
//                        alertDialog.dismiss();
//                    messageHandler.sendEmptyMessage(1);
                    face_text.setText("摄像头调起成功，开始人脸识别");
                    Smile(SzimId, SzimInitClientData);
                }
            } else if (requestUrl.endsWith("StartSmilePay")) {
                /*
                 * 如果支付成功之后返回我正确的信号，进行出货跳转界面的操作，出货之后跳，更新库存，上传订单信息，出货的方法
                 */

                String order = datas.optString("order");

                if (code.equals("0")) {
                    lastTime = System.currentTimeMillis();
                    actTime = lastTime - startTime;
                    L.i("tjf====sendPayOrder: 交易时间：" + (int) actTime);
                    //进行埋点上报的工作
                    CollectionAPI collectionAPI = APIManager.getInstance().getCollectionAPI();
                    collectionAPI.reportTradeData(true, NONE, null, TradeDataConstants.NetworkType._4G, (int) actTime);

                    messageHandler.sendEmptyMessage(3);

                } else {
                    lastTime = System.currentTimeMillis();
                    actTime = lastTime - startTime;
                    L.i("tjf===sendPayOrder: 交易超时的操作 ：" + (int) actTime);
                    //进行埋点上报的工作
                    CollectionAPI collectionAPI = APIManager.getInstance().getCollectionAPI();
                    collectionAPI.reportTradeData(false, NETWORK_EXCEPTION, null, TradeDataConstants.NetworkType._4G, (int) actTime);
                    messageHandler.sendEmptyMessage(2);
                }
            } else {
                messageHandler.sendEmptyMessage(7);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

    }
}
